from globals import *
from mysprite import MySprite

# basic snake logic
class BasicSnake:
	def __init__(self, grid, isHuman, segments, totalLength, symbol, direction):
		self.grid = grid
		self.isHuman = isHuman
		self.length = len(segments)
		self.totalLength = totalLength
		self.symbol = symbol
		self.direction = direction
		self.isAlive = True
		self.segments = []
		for segment in segments:
			self.segments.append(segment)
			grid.gmap[segment[0]][segment[1]].snakes.append(self) # grid tile update
	
	# this is slow, we rather let dead snakes on the grid (without impact)
	def leaveGrid(self):
		for segment in self.segments:
			x, y = segment
			snakes = self.grid.gmap[x][y].snakes
			self.grid.gmap[x][y].snakes = filter (lambda snake: snake != self, snakes)

	def update(self):
		newHead = addZip (self.segments[0]) (MOVEMODS[self.direction])
		# add new head
		self.segments.insert(0, newHead)
		self.length += 1
		# remove old tail
		oldTail = None
		if self.length == self.totalLength + 1:
			oldTail = self.segments.pop()
			self.length -= 1
		return newHead, oldTail

# snake also handling sprites of its segments
class Snake(BasicSnake):
	def __init__(self, grid, isHuman, color, segments, totalLength, symbol, direction):
		BasicSnake.__init__(self, grid, isHuman, segments, totalLength, symbol, direction)
		self.segmentSprites = []
		for segment in segments:
			self.segmentSprites.append(MySprite(color, segment))
		self.color = color
		self.inHeaven = False
		self.roundsNotAlive = 0

	def leaveGrid(self, sprites):
		#BasicSnake.leaveGrid(self) <- slow
		for segmentSprite in self.segmentSprites:
			sprites.move_to_back(segmentSprite) # be overdrawn
	
	def crashAnimation(self):
		self.roundsNotAlive += 1
		if self.roundsNotAlive > 6:
			for segmentSprite in self.segmentSprites:
				segmentSprite.kill()
			self.inHeaven = True # finally...
			return
		# blink blink
		if self.roundsNotAlive % 2 == 0:
			for segmentSprite in self.segmentSprites: 
				segmentSprite.image.set_alpha(0)
				segmentSprite.dirty = 1
		else:
			for segmentSprite in self.segmentSprites: 
				segmentSprite.image.set_alpha(200)
				segmentSprite.dirty = 1

	def update(self, sprites):
		newHead, oldTail = BasicSnake.update(self)
		newHeadSprite = MySprite(self.color, newHead)
		self.segmentSprites.insert(0, newHeadSprite) # add new head to segmentSprites
		sprites.add(newHeadSprite) # add it also to "global" sprites
		if oldTail != None:
			oldTailSprite = self.segmentSprites.pop() # remove old tail from segmentSprites
			sprites.remove(oldTailSprite) # remove it also from "global" sprites
		return newHead, oldTail
